<template>
  <div class="components">
    <div class="container">
      <h1>电脑配件库</h1>
      <p>浏览和筛选各种电脑配件，找到最适合你的装机部件</p>
      
      <!-- 配件类型选择器 -->
      <div class="component-type-selector">
        <button 
          v-for="type in componentTypes" 
          :key="type.id"
          :class="['component-type-btn', { active: selectedType === type.id }]"
          @click="selectComponent(type.id)"
        >
          <span class="btn-icon">{{ type.icon }}</span>
          {{ type.name }}
        </button>
      </div>

      <!-- 筛选器 -->
      <div class="filter-container" v-if="selectedType">
        <div class="filters">
          <div class="filter-group">
            <label>价格区间</label>
            <div class="price-range">
              <input type="number" v-model="priceRange.min" placeholder="最低价格" />
              <span>-</span>
              <input type="number" v-model="priceRange.max" placeholder="最高价格" />
              <button class="btn-filter" @click="applyFilters">筛选</button>
            </div>
          </div>
          
          <div class="filter-group">
            <label>排序方式</label>
            <select v-model="sortBy" @change="applyFilters">
              <option value="price-asc">价格从低到高</option>
              <option value="price-desc">价格从高到低</option>
              <option value="performance-asc">性能从低到高</option>
              <option value="performance-desc">性能从高到低</option>
              <option value="name-asc">名称A-Z</option>
              <option value="name-desc">名称Z-A</option>
            </select>
          </div>
          
          <button class="btn-coupon-search" @click="toggleCouponSearch">
            🔍 优惠券搜索
          </button>
        </div>
      </div>
      
      <!-- 优惠券搜索面板 -->
      <div v-if="showCouponSearch" class="coupon-search-panel">
        <div class="search-header">
          <h3>搜索配件优惠券</h3>
          <button class="close-btn" @click="toggleCouponSearch">×</button>
        </div>
        <div class="search-input-group">
          <input 
            type="text" 
            v-model="couponSearchKeyword" 
            placeholder="输入配件名称搜索优惠券..."
            @keyup.enter="handleCouponSearch"
          />
          <button @click="handleCouponSearch" :disabled="isSearching">
            {{ isSearching ? '搜索中...' : '搜索' }}
          </button>
        </div>
        <div class="search-results">
          <div v-if="isSearching" class="loading">搜索中...</div>
          <div v-else-if="searchResults.length > 0" class="coupons-list">
            <div v-for="coupon in searchResults" :key="coupon.id" class="coupon-item">
              <div class="coupon-platform">{{ coupon.platform }}</div>
              <div class="coupon-info">
                <div class="coupon-product">{{ coupon.productName }}</div>
                <div class="coupon-discount">{{ coupon.discount }}</div>
                <div class="coupon-expire">有效期至: {{ coupon.expireDate }}</div>
              </div>
              <a :href="coupon.link" target="_blank" class="btn-view-coupon">查看</a>
            </div>
          </div>
          <div v-else-if="couponSearchKeyword && !isSearching" class="no-results">
            未找到相关优惠券
          </div>
        </div>
      </div>

      <!-- 配件列表 -->
      <div class="components-grid" v-if="filteredComponents.length > 0">
        <div class="component-card" v-for="component in filteredComponents" :key="component.id">
          <div class="component-image">
            <img :src="component.image" :alt="component.name" class="component-img">
          </div>
          <div class="component-header">
            <h3>{{ component.name }}</h3>
            <div class="component-price">
                <template v-if="isVip">
                  <span class="vip-price">¥{{ getVipPrice(component).toLocaleString() }}</span>
                  <span class="original-price">¥{{ component.price.toLocaleString() }}</span>
                  <span class="savings">省¥{{ calculateSavings(component.price).toLocaleString() }}</span>
                </template>
                <template v-else>
                  ¥{{ component.price.toLocaleString() }}
                </template>
              </div>
          </div>
          
          <div class="component-body">
            <div class="component-specs">
              <div v-if="selectedType === 'cpu'" class="spec-item">
                <span class="spec-label">核心数:</span>
                <span class="spec-value">{{ component.coreCount }}核 {{ component.threadCount }}线程</span>
              </div>
              
              <div v-if="selectedType === 'cpu'" class="spec-item">
                <span class="spec-label">频率:</span>
                <span class="spec-value">{{ component.baseFrequency }}GHz (最高 {{ component.boostFrequency }}GHz)</span>
              </div>
              
              <div v-if="selectedType === 'cpu'" class="spec-item">
                <span class="spec-label">接口:</span>
                <span class="spec-value">{{ component.socketType }}</span>
              </div>
              
              <div v-if="selectedType === 'gpu'" class="spec-item">
                <span class="spec-label">显存:</span>
                <span class="spec-value">{{ component.memory }}GB {{ component.memoryType }}</span>
              </div>
              
              <div v-if="selectedType === 'gpu'" class="spec-item">
                <span class="spec-label">频率:</span>
                <span class="spec-value">{{ component.coreClock }}MHz (最高 {{ component.boostClock }}MHz)</span>
              </div>
              
              <div v-if="selectedType === 'ram'" class="spec-item">
                <span class="spec-label">容量:</span>
                <span class="spec-value">{{ component.capacity }}GB ({{ component.modules }}条)</span>
              </div>
              
              <div v-if="selectedType === 'ram'" class="spec-item">
                <span class="spec-label">类型/频率:</span>
                <span class="spec-value">{{ component.type }} {{ component.frequency }}MHz</span>
              </div>
              
              <div v-if="selectedType === 'motherboard'" class="spec-item">
                <span class="spec-label">接口/芯片组:</span>
                <span class="spec-value">{{ component.socketType }} / {{ component.chipset }}</span>
              </div>
              
              <div v-if="selectedType === 'motherboard'" class="spec-item">
                <span class="spec-label">内存支持:</span>
                <span class="spec-value">{{ component.memoryType }} ({{ component.memorySlots }}插槽)</span>
              </div>
              
              <div v-if="selectedType === 'storage'" class="spec-item">
                <span class="spec-label">容量/类型:</span>
                <span class="spec-value">{{ component.capacity }}GB {{ component.type }}</span>
              </div>
              
              <div v-if="selectedType === 'storage'" class="spec-item">
                <span class="spec-label">速度:</span>
                <span class="spec-value">读 {{ component.readSpeed }}MB/s / 写 {{ component.writeSpeed }}MB/s</span>
              </div>
              
              <div v-if="selectedType === 'powerSupply'" class="spec-item">
                <span class="spec-label">功率/认证:</span>
                <span class="spec-value">{{ component.wattage }}W {{ component.efficiency }}</span>
              </div>
              
              <div v-if="selectedType === 'powerSupply'" class="spec-item">
                <span class="spec-label">模组类型:</span>
                <span class="spec-value">{{ component.modular }}</span>
              </div>
              
              <div v-if="selectedType === 'case'" class="spec-item">
                <span class="spec-label">规格:</span>
                <span class="spec-value">{{ component.formFactor }}</span>
              </div>
              
              <div v-if="selectedType === 'cpuCooler'" class="spec-item">
                <span class="spec-label">类型:</span>
                <span class="spec-value">{{ component.type }}</span>
              </div>
            </div>
          </div>
          
          <div class="component-footer">
            <div class="performance-score">
              <span>性能评分</span>
              <div class="score-bar">
                <div class="score-fill" :style="{ width: component.performanceScore + '%' }"></div>
              </div>
              <span class="score-number">{{ component.performanceScore }}</span>
            </div>
            <button class="btn-add-to-build">添加到配置</button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="selectedType">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="8" x2="12" y2="12"></line>
            <line x1="12" y1="16" x2="12.01" y2="16"></line>
          </svg>
        </div>
        <h3>没有找到符合条件的配件</h3>
        <p>请尝试调整筛选条件或选择其他类型的配件</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import type { PCComponent } from '../types/components';
import type { User, VipInfo } from '../types/vip';
import { 
  cpus, gpus, rams, motherboards, storages, 
  powerSupplies, pcCases, cpuCoolers 
} from '../data/mockData';
import { getUserWithVipInfo, isVipActive, calculateVipPrice, searchCoupons } from '../utils/vipService';

// 配件类型定义
interface ComponentType {
  id: string;
  name: string;
  icon: string;
}

// 配件类型列表
const componentTypes: ComponentType[] = [
  { id: 'cpu', name: 'CPU', icon: '🖥️' },
  { id: 'gpu', name: '显卡', icon: '🎮' },
  { id: 'ram', name: '内存', icon: '🧠' },
  { id: 'motherboard', name: '主板', icon: '🔌' },
  { id: 'storage', name: '存储', icon: '💾' },
  { id: 'powerSupply', name: '电源', icon: '⚡' },
  { id: 'case', name: '机箱', icon: '📦' },
  { id: 'cpuCooler', name: 'CPU散热器', icon: '❄️' }
];

// 用户状态
const user = ref<User | null>(null);
const showCouponSearch = ref(false);
const couponSearchKeyword = ref('');
const searchResults = ref<any[]>([]);
const isSearching = ref(false);

// 是否为VIP用户
const isVip = computed(() => isVipActive(user.value?.vipInfo));

// 获取组件的VIP价格
  const getVipPrice = (component: any) => {
    return calculateVipPrice(component.price, user.value?.vipInfo);
  };

// 计算节省金额
  const calculateSavings = (originalPrice: number) => {
    const vipPrice = calculateVipPrice(originalPrice, user.value?.vipInfo);
    return Math.round((originalPrice - vipPrice) * 100) / 100;
  };

// 搜索优惠券
  const handleCouponSearch = async () => {
    if (!couponSearchKeyword.value.trim()) return;
    
    isSearching.value = true;
    try {
      // 模拟搜索延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      searchResults.value = searchCoupons(couponSearchKeyword.value, user.value?.vipInfo);
    } finally {
      isSearching.value = false;
    }
  };

// 切换优惠券搜索面板
const toggleCouponSearch = () => {
  if (!isVip.value) {
    alert('请升级到白银及以上会员以使用优惠券搜索功能');
    return;
  }
  showCouponSearch.value = !showCouponSearch.value;
  if (!showCouponSearch.value) {
    searchResults.value = [];
    couponSearchKeyword.value = '';
  }
};

// 加载用户信息
const loadUserInfo = () => {
  user.value = getUserWithVipInfo();
};

// 选中的配件类型
const selectedType = ref<string>('cpu');

// 价格区间筛选
const priceRange = ref({
  min: '',
  max: ''
});

// 排序方式
const sortBy = ref<string>('performance-desc');

// 当前显示的配件列表
const currentComponents = ref<any[]>([]);

// 筛选后的配件列表
const filteredComponents = computed(() => {
  let components = [...currentComponents.value];
  
  // 价格筛选
  if (priceRange.value.min) {
    components = components.filter(comp => comp.price >= Number(priceRange.value.min));
  }
  
  if (priceRange.value.max) {
    components = components.filter(comp => comp.price <= Number(priceRange.value.max));
  }
  
  // 排序
  switch (sortBy.value) {
    case 'price-asc':
      components.sort((a, b) => a.price - b.price);
      break;
    case 'price-desc':
      components.sort((a, b) => b.price - a.price);
      break;
    case 'performance-asc':
      components.sort((a, b) => a.performanceScore - b.performanceScore);
      break;
    case 'performance-desc':
      components.sort((a, b) => b.performanceScore - a.performanceScore);
      break;
    case 'name-asc':
      components.sort((a, b) => a.name.localeCompare(b.name));
      break;
    case 'name-desc':
      components.sort((a, b) => b.name.localeCompare(a.name));
      break;
  }
  
  return components;
});

// 选择配件类型
const selectComponent = (type: string) => {
  selectedType.value = type;
  loadComponents(type);
  // 重置筛选条件
  priceRange.value = { min: '', max: '' };
  sortBy.value = 'performance-desc';
};

// 加载配件数据
const loadComponents = (type: string) => {
  switch (type) {
    case 'cpu':
      currentComponents.value = cpus;
      break;
    case 'gpu':
      currentComponents.value = gpus;
      break;
    case 'ram':
      currentComponents.value = rams;
      break;
    case 'motherboard':
      currentComponents.value = motherboards;
      break;
    case 'storage':
      currentComponents.value = storages;
      break;
    case 'powerSupply':
      currentComponents.value = powerSupplies;
      break;
    case 'case':
      currentComponents.value = pcCases;
      break;
    case 'cpuCooler':
      currentComponents.value = cpuCoolers;
      break;
    default:
      currentComponents.value = [];
  }
};

// 应用筛选
const applyFilters = () => {
  // 筛选逻辑已在computed中实现
};

// 添加到配置
const addToBuild = (component: any) => {
  // 在实际应用中，这里会将配件添加到用户的装机配置中
  alert(`${component.name} 已添加到配置！`);
};

// 组件挂载时加载初始数据
onMounted(() => {
  loadComponents(selectedType.value);
  loadUserInfo();
  
  // 监听storage事件，以便在其他标签页登录/购买VIP时更新
  window.addEventListener('storage', (e) => {
    if (e.key === 'user' || e.key?.includes('vip_')) {
      loadUserInfo();
    }
  });
});
</script>

<style scoped>
.components {
  padding: 3rem 0;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

.components h1 {
  text-align: center;
  font-size: 2.5rem;
  margin: 0 0 0.5rem 0;
  color: #1a1a1a;
}

.components p {
  text-align: center;
  color: #666;
  margin: 0 0 3rem 0;
  font-size: 1.1rem;
}

/* 配件类型选择器 */
.component-type-selector {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  justify-content: center;
  margin-bottom: 2rem;
}

.component-type-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: 2px solid #ddd;
  background-color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  font-weight: 500;
}

.component-type-btn:hover {
  border-color: #00ccff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 204, 255, 0.2);
}

.component-type-btn.active {
  background-color: #00ccff;
  border-color: #00ccff;
  color: white;
}

.btn-icon {
  font-size: 1.2rem;
}

/* 筛选器 */
.filter-container {
  background-color: white;
  padding: 1.5rem;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.filters {
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.filter-group label {
  font-weight: 600;
  color: #1a1a1a;
  white-space: nowrap;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.price-range input {
  width: 100px;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.price-range span {
  color: #666;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  background-color: white;
  cursor: pointer;
}

.btn-filter {
  padding: 0.5rem 1rem;
  background-color: #00ccff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-filter:hover {
  background-color: #00a3cc;
}

/* 配件网格 */
.components-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
}

/* 配件卡片 */
.component-card {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 配件图片 */
.component-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  background-color: #f0f0f0;
}

.component-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.component-card:hover .component-img {
  transform: scale(1.05);
}

.component-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}

.component-header {
  background-color: #1a1a1a;
  color: white;
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.component-header h3 {
  margin: 0;
  font-size: 1.2rem;
  line-height: 1.4;
}

.component-price {
  font-size: 1.2rem;
  font-weight: bold;
  color: #00ccff;
}

/* VIP价格显示 */
.vip-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 1.3rem;
  margin-right: 0.5rem;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 0.9rem;
  margin-right: 0.5rem;
}

.savings {
  color: #52c41a;
  font-size: 0.9rem;
  font-weight: bold;
}

/* 优惠券搜索按钮 */
.btn-coupon-search {
  background-color: #ff7a45;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
}

.btn-coupon-search:hover {
  background-color: #ff4d1a;
}

/* 优惠券搜索面板 */
.coupon-search-panel {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-top: 1rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.search-header h3 {
  margin: 0;
  color: #1a1a1a;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #1a1a1a;
}

.search-input-group {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.search-input-group input {
  flex: 1;
  padding: 0.75rem;
  border: 2px solid #eaeaea;
  border-radius: 4px;
  font-size: 1rem;
}

.search-input-group input:focus {
  outline: none;
  border-color: #00ccff;
}

.search-input-group button {
  padding: 0.75rem 1.5rem;
  background-color: #00ccff;
  color: #1a1a1a;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-input-group button:hover:not(:disabled) {
  background-color: #00a3cc;
}

.search-input-group button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.no-results {
  text-align: center;
  padding: 2rem;
  color: #999;
}

/* 优惠券列表 */
.coupons-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.coupon-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.coupon-item:hover {
  background-color: #e6f7ff;
}

.coupon-platform {
  background-color: #1890ff;
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 4px;
  font-weight: bold;
  font-size: 0.9rem;
  white-space: nowrap;
}

.coupon-info {
  flex: 1;
}

.coupon-product {
  font-weight: bold;
  color: #1a1a1a;
  margin-bottom: 0.25rem;
}

.coupon-discount {
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 0.25rem;
}

.coupon-expire {
  color: #999;
  font-size: 0.9rem;
}

.btn-view-coupon {
  background-color: #52c41a;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  text-decoration: none;
  font-weight: bold;
  transition: background-color 0.3s ease;
}

.btn-view-coupon:hover {
  background-color: #389e0d;
}

.component-body {
  padding: 1.5rem;
}

.component-specs {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.spec-item {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.spec-label {
  font-weight: 600;
  color: #666;
  min-width: 80px;
}

.spec-value {
  color: #1a1a1a;
  flex: 1;
}

.component-footer {
  padding: 1.5rem;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.performance-score {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.performance-score span:first-child {
  font-size: 0.9rem;
  color: #666;
}

.score-bar {
  width: 80px;
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.score-fill {
  height: 100%;
  background-color: #00ccff;
  transition: width 0.3s ease;
}

.score-number {
  font-weight: bold;
  color: #1a1a1a;
  min-width: 30px;
  text-align: right;
}

.btn-add-to-build {
  padding: 0.75rem 1.5rem;
  background-color: #00ccff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-add-to-build:hover {
  background-color: #00a3cc;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 4rem 0;
}

.empty-icon {
  color: #ddd;
  margin-bottom: 1rem;
}

.empty-state h3 {
  color: #1a1a1a;
  margin: 0 0 0.5rem 0;
  font-size: 1.5rem;
}

.empty-state p {
  color: #666;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .components h1 {
    font-size: 2rem;
  }
  
  .component-type-selector {
    justify-content: flex-start;
  }
  
  .components-grid {
    grid-template-columns: 1fr;
  }
  
  .filters {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    width: 100%;
  }
  
  .price-range {
    width: 100%;
  }
  
  .price-range input {
    flex: 1;
  }
  
  .filter-group select {
    width: 100%;
  }
  
  .component-footer {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .performance-score {
    justify-content: space-between;
  }
  
  .btn-add-to-build {
    width: 100%;
  }
}
</style>